<template>
  <div class="indexContainer">
    <img v-if="isShow" class="index_img" :src="userInfo.avatarUrl" alt="">
    <Button class="btn" v-else open-type="getUserInfo" @getuserinfo="getUserInfo">点击获取授权</Button>
    <p class="userName">hello {{userInfo.nickName}}</p>
    <div v-if="isShow" @tap="toDetail" class="goStudy">
      <p>开启答题闯关之旅</p>
    </div>
    <div v-if="!isRegiste">
      <button type="primary" @click="showPicker" >第一次注册，请选择年级</button>
    </div>
    <mp-picker ref="mpPicker" :mode="mode"
               @onConfirm="toRegiste"  :pickerValueArray="pickerValueArray"></mp-picker>
  </div>
</template>
<script>
  import mpPicker from 'mpvue-weui/src/picker'
  import {addUserInfo} from '../../util/api'

  export default {
    components: {
      mpPicker
    },
    data () {
      return {
        encryptedData: '', // 微信数据
        iv: '', // 微信数据解密向量
        userInfo: {}, // 从微信拿回来的数据
        isShow: false, // 是否显示进主页面的按钮
        isRegiste: true, // 是否注册过
        mode: 'selector',
        // picker组件的数据
        pickerValueArray: [
          {
            label: '一年级',
            value: 1
          },
          {
            label: '二年级',
            value: 2
          },
          {
            label: '三年级',
            value: 3
          },
          {
            label: '四年级',
            value: 4
          },
          {
            label: '五年级',
            value: 5
          },
          {
            label: '六年级',
            value: 6
          }
        ]
      }
    },

    beforeMount () {
      // 判断本地是否有缓存数据
      var isAuthorize = wx.getStorageSync('isAuthorize')
      if (isAuthorize === true) {
        this.isShow = true
        this.userInfo = wx.getStorageSync('userInfo')
        this.$store.state.openid = wx.getStorageSync('openid')
      }
    },
    methods: {
      // 获取用户登录信息
      getUserInfo (data) {
        // 判断用户是否授权
        if (data.mp.detail.userInfo) {
          // 用户按了允许授权按钮
          this.encryptedData = data.mp.detail.encryptedData
          this.iv = data.mp.detail.iv
          this.userInfo = data.mp.detail.userInfo
          wx.setStorage({
            key: 'isAuthorize',
            data: true
          })
          wx.setStorage({
            key: 'userInfo',
            data: this.userInfo
          })
          this.login()
        } else {
          // 用户按了拒绝按钮
          console.log('拒绝授权')
        }
      },
      toDetail () {
        // 跳转到主页
        wx.redirectTo({
          url: '/pages/main/main'
        })
      },
      login () {
        let _that = this
        wx.login({
          success: function (res) {
            console.log(res.code) // 从wx.login拿到code
            // 向后端请求登录
            wx.request({
              url: _that.$store.state.URL + '/studygo/userLogin', // 接口地址
              data: {code: res.code,
                encryptedData: _that.encryptedData,
                iv: _that.iv
              },
              method: 'POST',
              header: {
                'content-type': 'application/json' // 默认值
              },
              success: function (res) {
                // 用户第一次注册
                if (res.data.message.indexOf('saveUser') !== -1) {
                  _that.isRegiste = false
                  wx.setStorage({
                    key: 'openid',
                    data: res.data.data.unionId
                  })
                  _that.$store.state.openid = res.data.data.unionId
                } else { // 不是第一次注册
                  _that.isShow = true
                  wx.setStorage({
                    key: 'openid',
                    data: res.data.data.username
                  })
                  wx.setStorage({
                    key: 'userId',
                    data: res.data.data.id
                  })
                  _that.$store.state.openid = wx.getStorageSync('openid')
                  _that.$store.state.userId = wx.getStorageSync('userId')
                }
              }
            })
          }
        })
      },
      showPicker () {
        this.$refs.mpPicker.show()
      },
      toRegiste (e) { // 用户第一次注册
        let _that = this
        wx.request({ // 向后端注册用户
          url: _that.$store.state.URL + '/studygo/saveUser',
          data: {
            username: wx.getStorageSync('openid'),
            nickname: _that.userInfo.nickName,
            grade: e.label
          },
          method: 'POST',
          header: {
            'content-type': 'application/json' // 默认值
          },
          success (res) {
            _that.toAddUserInfo(e.label) // 向题库注册新用户
            _that.isRegiste = true
            _that.isShow = true
            wx.setStorage({
              key: 'userId',
              data: res.data.data.id
            })
            _that.$store.state.userId = wx.getStorageSync('userId')
          }
        })
      },
      toAddUserInfo (grade) {
        addUserInfo(grade, this.$store.state.openid)
          .then((response) => {
            console.log(response)
          })
          .catch((error) => {
            console.log(error)
          })
      }
    }
  }
</script>
<style>
  page {
    background-image: url();
  }

  .indexContainer {
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .index_img {
    display: flex;
    width: 100px;
    height: 100px;
    border-radius: 98rpx;
    justify-content: center;
    align-items: center;
    margin-top: 150px;
  }

  .userName {
    font-size: 70 rpx;
    font-family: "华文楷体";
    color: dodgerblue;
    font-weight: bold;
    margin: 100 rpx 0;
  }

  .goStudy {
    background: dodgerblue;
    color: #ffffff;
    width: 220 rpx;
    height: 80 rpx;
    border: 5rpx solid #ffffff;
    font-size: 48 rpx;
    font-family: "华文楷体";
    font-weight: bolder;
    line-height: 80 rpx;
    text-align: center;
    border-radius: 10 rpx;
  }

  .btn {
    width: 300 rpx;
    height: 300 rpx;
    border-radius: 150 rpx;
    margin: 50 rpx 0;
    line-height: 300 rpx;
    text-align: center;
    font-size: 26 rpx;
  }

</style>
